package cn.fetosoft.woodpecker.interceptor;

import cn.fetosoft.woodpecker.config.Constant;
import cn.fetosoft.woodpecker.controller.Result;
import cn.fetosoft.woodpecker.struct.UserIdentity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

/**
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/6/8 14:47
 */
public class LimitInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);
	private static final String AJAX_HEADER = "XMLHttpRequest";
	private Set<String> ignoreSet = new HashSet<>();

	public LimitInterceptor(){
		ignoreSet.add("nologins:/login");
		ignoreSet.add("nologins:/userLogin");
		ignoreSet.add("nologins:/acceptForm");
		ignoreSet.add("nologins:/acceptBody");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI().substring(request.getContextPath().length());
		if(StringUtils.isBlank(uri) || uri.indexOf("/error")==0
				|| ignoreSet.contains("nologins:" + uri)){
			return true;
		}else{
			String ajaxHeader = request.getHeader("X-Requested-With");
			HttpSession session = request.getSession();
			UserIdentity user = (UserIdentity) session.getAttribute(Constant.SESSION_USER);
			if(user!=null){
				return true;
			}else{
				if(AJAX_HEADER.equalsIgnoreCase(ajaxHeader)){
					PrintWriter out = response.getWriter();
					Result<String> result = Result.create(Result.LOGIN);
					result.setErrorMsg("Please login!!!");
					out.write(result.toString());
					out.flush();
					out.close();
				}else {
					response.sendRedirect(request.getContextPath() + "/login");
				}
				return false;
			}
		}
	}
}
